import styles from './CustomTimeCard.module.scss'
import {Form, DatePicker} from 'antd-mobile'
import {useEffect,RefObject} from 'react'
import type { DatePickerRef } from 'antd-mobile/es/components/date-picker'
import dayjs from 'dayjs'
export default function(props:{
  cancel: ()=>void,
  sendDateForm: (obj: ItemListDateParam)=>void
}){
  const [form] = Form.useForm()

  const defaultValueObj={ happened_after: undefined, happened_before: undefined }
  useEffect(() => {
    form.setFieldsValue(defaultValueObj)
  }, [])
  const handleCancel = () => {
    props.cancel()
  }
  const onSubmit = () => {
    const formData = form.getFieldsValue()
    const obj = {
      happened_after: dayjs(formData.happened_after).format('YYYY-MM-DD'),
      happened_before: dayjs(formData.happened_before).format('YYYY-MM-DD')
    }
    props.sendDateForm(obj)
  }
  const validateEndTime = (_: any, value: Date) => {
    const startTime = form.getFieldValue('happened_after');
    if (startTime && value && dayjs(value).isBefore(dayjs(startTime))) {
      return Promise.reject(new Error('开始时间不能大于结束时间!'))
    } else {
      return Promise.resolve()
    }
  };
  return  (
    <div className={styles.customTimeCard}>
      <header>请选择时间</header>
      <main>
        <Form
          form={form}
          layout='horizontal' mode='card'
          onFinish={onSubmit}
          footer={
            <>
              <button type='button' onClick={handleCancel}>取消</button>
              <button type='submit' className="text-[var(--adm-color-primary)]">确定</button>
            </>
          }
        >
          <Form.Item
            name='happened_after'
            label='开始时间'
            trigger='onConfirm'
            onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
              datePickerRef.current?.open()
            }}
            rules={[ 
              { required: true, message: '请选择开始时间' }
            ]}
          >
            <DatePicker>
              {value => value ? dayjs(value).format('YYYY-MM-DD') : '请选择日期' }
            </DatePicker>
          </Form.Item>
          <Form.Item
            name='happened_before'
            label='结束时间'
            trigger='onConfirm'
            onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
              datePickerRef.current?.open()
            }}
            rules={[ 
              { required: true, message: '请选择结束时间' },
              { validator: validateEndTime }
            ]}
          >
            <DatePicker>
              {value => value ? dayjs(value).format('YYYY-MM-DD') : '请选择日期' }
            </DatePicker>
          </Form.Item>
        </Form>
      </main>
    </div>
  )
}